package com.ledi.guns.modular.system.service.impl;

import javax.annotation.Resource;

import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import com.ledi.guns.common.persistence.dao.RelationMapper;
import com.ledi.guns.common.persistence.dao.RoleMapper;
import com.ledi.guns.common.persistence.dao.RoutesRoleMapper;
import com.ledi.guns.common.persistence.model.Relation;
import com.ledi.guns.common.persistence.model.RoutesRole;
import com.ledi.guns.core.util.Convert;
import com.ledi.guns.modular.system.dao.RoleDao;
import com.ledi.guns.modular.system.service.IRoleService;

@Service
public class RoleServiceImpl implements IRoleService {

	@Resource
	RoleMapper roleMapper;

	@Resource
	RoleDao roleDao;

	@Resource
	RelationMapper relationMapper;

	@Resource
	RoutesRoleMapper routesRoleMapper;

	@Override
	@Transactional(readOnly = false)
	public void setAuthority(Integer roleId, String ids) {

		// 删除该角色所有的权限
		roleDao.deleteRolesById(roleId);

		// 添加新的权限
		for (Integer id : Convert.toIntArray(ids)) {
			Relation relation = new Relation();
			relation.setRoleid(roleId);
			relation.setMenuid(id);
			relationMapper.insert(relation);
		}
	}

	@Override
	@Transactional(readOnly = false)
	public void delRoleById(Integer roleId) {

		// 删除角色
		roleMapper.deleteById(roleId);

		// 删除该角色所有的权限
		roleDao.deleteRolesById(roleId);
	}

	@Override
	public void setRoutes(Integer roleId, String ids) {

		// 删除该角色所有的路由
		roleDao.deleteRoutesById(roleId);

		// 添加新的权限
		for (Integer id : Convert.toIntArray(ids)) {
			RoutesRole relation = new RoutesRole();
			relation.setRoleid(roleId);
			relation.setRoutesid(id);
			routesRoleMapper.insert(relation);
		}
	}

}
